package com.ruben.leetCode;/**
 * @ClassName: SortByBitsSolution
 * @Date: 2020/11/6 0006 22:39
 * @Description:
 */

import java.util.*;
import java.util.function.IntFunction;

/**
 * @ClassName: SortByBitsSolution
 * @Description: 我还没有写描述
 * @Date: 2020/11/6 0006 22:39
 * *
 * @author: <achao1441470436@gmail.com>
 * @version: 1.0
 * @since: JDK 1.8
 */
public class SortByBitsSolution {
    public static void main(String[] args) {
        SortByBitsSolution solution = new SortByBitsSolution();
        int[] ints = solution.sortByBit(new int[]{1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1});
        Arrays.stream(Optional.ofNullable(ints).orElse(new int[0])).forEach(System.out::println);
    }

    public int[] sortByBit(int[] arr) {
        return Arrays.stream(arr).map(n -> Integer.bitCount(n) * 100544 + n).sorted().map(n -> n % 100544).toArray();
    }

    /**
     * @MethodName: sortByBits
     * @Description: 根据数字二进制下 1 的数目排序
     * @Date: 2020/11/6 0006 23:22
     * *
     * @author: <achao1441470436@gmail.com>
     * @param: [arr]
     * @returnValue: int[]
     */
    public int[] sortByBits(int[] arr) {
        return Arrays.stream(arr)
                .boxed()
                .sorted((o1, o2) -> {
                    long oneCount = Integer.bitCount(o1);
                    long twoCount = Integer.bitCount(o2);
                    if (oneCount > twoCount) {
                        return 1;
                    } else if (oneCount < twoCount) {
                        return -1;
                    } else {
                        return Integer.compare(o1, o2);
                    }
                }).mapToInt(Integer::intValue).toArray();
    }

    /**
     * @MethodName: deBit
     * @Description: 十进制转二进制
     * @Date: 2020/11/6 0006 22:49
     * *
     * @author: <achao1441470436@gmail.com>
     * @param: [n]
     * @returnValue: java.util.List<java.lang.String>
     */
    public List<String> deBit(int n) {
        List<String> list = new ArrayList<>(1 << 5);
        for (int i = 31; i >= 0; i--) {
            list.add(String.valueOf(n >>> i & 1));
        }
        return list;
    }
}
